
package com.kweative.util;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.Stack;

/**
 *
 * @author henrik
 */
public class ReflectUtil {
    public static Class primitives[] = {Boolean.class,Integer.class,Double.class,String.class,Float.class,Short.class,Byte.class,char.class,Long.class};
    public static Method[] getMethod(Class clazz,String name) {
        Stack<Method> result = new Stack<Method>();
        Method methods[] = clazz.getDeclaredMethods();
        for(Method method:methods) {
            if (method.getName().equalsIgnoreCase(name))
                result.add(method);

        }
        return result.toArray(new Method[0]);
    }
    public static boolean isPrimitive(Class clazz) {
        if (clazz.isPrimitive()) return true;
        for(Class primitive:primitives) {
            if (primitive.equals(clazz))
                return true;
        }
        return false;
    }
    public static Class[] getClasses(String pckgname) throws ClassNotFoundException {
        return getClasses(pckgname,null,null);
    }
    public static Class[] getClasses(String pckgname,Object helperObject) throws ClassNotFoundException {
        return getClasses(pckgname, null, helperObject);
    }
    public static Class[] getClasses(String pckgname,Class superClass,Object helperObject)
			throws ClassNotFoundException {
		ArrayList<Class> classes = new ArrayList<Class>();
		// Get a File object for the package
		File directory = null;
		try {
            ClassLoader cld = Thread.currentThread().getContextClassLoader();

			
			if (cld == null) {
				throw new ClassNotFoundException("Can't get class loader.");
			}
			String path = pckgname.replace('.', '/');
			URL resource = cld.getResource(path);
			if (resource == null) {
				throw new ClassNotFoundException("No resource for " + path);
			}
			directory = new File(resource.getFile());
		} catch (NullPointerException x) {
			throw new ClassNotFoundException(pckgname + " (" + directory
					+ ") does not appear to be a valid package");
		}
		if (directory.exists()) {
			// Get the list of the files contained in the package
			String[] files = directory.list();
			for (int i = 0; i < files.length; i++) {
				// we are only interested in .class files
				if (files[i].endsWith(".class")) {
					// removes the .class extension
                    Class cls = Class.forName(pckgname + '.'
							+ files[i].substring(0, files[i].length() - 6));

                    if (superClass != null && !superClass.isAssignableFrom(cls))
                        continue;
					classes.add(cls);
				}
			}
		} else {
			throw new ClassNotFoundException(pckgname
					+ " does not appear to be a valid package");
		}
		
		return classes.toArray(new Class[0]);
	}
}
